package com.eastfair.common.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.common.dao.CommonInterfaceCallRecordMapper;
import com.eastfair.common.entity.CommonInterfaceCallRecord;
import com.eastfair.common.res.LogisticsRes;
import com.eastfair.common.service.CommonInterfaceCallRecordService;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * <p>
 * 业务实现类
 *
 * </p>
 *
 * @author clm
 * @date 2022-12-29
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class CommonInterfaceCallRecordServiceImpl extends SuperServiceImpl<CommonInterfaceCallRecordMapper, CommonInterfaceCallRecord> implements CommonInterfaceCallRecordService {

    @Value("${com.eastfair.projectId}")
    private Long projectId;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<CommonInterfaceCallRecord> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(CommonInterfaceCallRecord model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public String processHttp(String httpUrl, Object attr, String callbackUrl, String traceId, String romaXHWID, String romaXHWAPPKEY) {
        log.info("processHttp - 发送请求，记录请求日志, httpUrl={}, httpAttr={}", httpUrl, JSONObject.toJSONString(attr));
        String httpAttr = JSONObject.toJSONString(attr);
        CommonInterfaceCallRecord commonInterfaceCallRecord = new CommonInterfaceCallRecord();
        commonInterfaceCallRecord.setRetryCount(0);
        commonInterfaceCallRecord.setMaxRetryCount(5);
        commonInterfaceCallRecord.setTraceId(traceId);
        commonInterfaceCallRecord.setCallbackUrl(callbackUrl);
        commonInterfaceCallRecord.setProjectId(projectId);

        String body = null;
        try (HttpResponse miceHttp = HttpRequest
                .post(httpUrl)
                .header("X-HW-ID", romaXHWID)
                .header("X-HW-APPKEY", romaXHWAPPKEY)
                .contentType("application/json")
                .body(httpAttr)
                .timeout(10000)
                .execute()) {

            if (miceHttp.isOk()) {
                body = miceHttp.body();
                log.info("processHttp - 发送请求,返回结果, body={}", body);
                LogisticsRes logisticsRes = JSONObject.parseObject(body, LogisticsRes.class);
                commonInterfaceCallRecord.setStatus(1);
                commonInterfaceCallRecord.setBusinessCode(logisticsRes.getRetCode());
                commonInterfaceCallRecord.setErrorMsg(body);
            } else {
                commonInterfaceCallRecord.setStatus(-1);
            }
            commonInterfaceCallRecord.setHttpCode(miceHttp.getStatus());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            commonInterfaceCallRecord.setErrorMsg(e.getMessage());
            commonInterfaceCallRecord.setStatus(-1);
        }
        commonInterfaceCallRecord.setHttpUrl(httpUrl);
        commonInterfaceCallRecord.setHttpAttr(httpAttr);
        commonInterfaceCallRecord.setHttpType("POST");
        save(commonInterfaceCallRecord);
        return body;
    }

    @Override
    public String processHttp(String httpUrl, Object attr, String callbackUrl, String romaXHWID, String romaXHWAPPKEY) {
        String traceId = UUID.randomUUID().toString();
        return processHttp(httpUrl, attr, callbackUrl, traceId, romaXHWID, romaXHWAPPKEY);
    }

    @Override
    public String processHttp(String httpUrl, Object attr, String romaXHWID, String romaXHWAPPKEY) {
        return processHttp(httpUrl, attr, null, romaXHWID, romaXHWAPPKEY);
    }

    /**
     * Process http string.
     *
     * @param httpUrl the http url
     * @param attr    the attr
     * @return the string
     */
    @Override
    public String processHttp(String httpUrl, Object attr) {
        return processHttp(httpUrl, attr, null, null);
    }
}
